<script setup>
import {getCurrentInstance, nextTick, ref, watch} from "vue";
import InputTable from "@/views/lims/InputTable"
import WfInputTable from "@/components/wanfengComponents/WfInputTable.vue";
import {getTableRecord, saveFormData} from "@/api/lims/sysManager/table";
import {getDecodeData} from "@/api/lims/sop";
import {LimsConfig, LimsFormConfig} from "@/api/lims/common/LimsModel";
import {parseParams} from "@/utils/ruoyi";
import {setNullToEmpty, sleep} from "@/utils/wanfeng";
import {getActionStatusMapByTemplate, saveWorkFlow} from "@/api/lims/sysManager/workFlow";
import {getVersionAnalysis, sampleLog} from "@/api/lims/sample/sample";
import moment from "moment";
const {proxy} = getCurrentInstance()
const sampleForm = ref()
const formData = ref({
  IS_REPORT: '否',
  productName: '',
  MLP_ID:'',
  TEST_SCHEDULE:'',
  S_MATERIAL_ID:'',
})

const queryConfig = ref({
  sql: 'select * from S_MATERIAL WHERE 1=1 ',
  columns: [
    {label: '标识', name: '[IDENTITY]', isQuery: true},
    {label: '名称', name: 'NAME', isQuery: true},
    {label: '描述', name: 'DESCRIPTION', isQuery: true},
    {label: '产品标准', name: 'PRODUCT_NAME', isQuery: true},
    {label: '产品规格', name: 'PRODUCT_SPEC', isQuery: true},
    {label: '产品类型', name: 'PRODUCT_TYPE', isQuery: true},
  ],
  page:{
    isPage: true,
    order: '[IDENTITY]',
  },
  valueFiled:'NAME'
})
const specConfig = ref({
  sql: ' select * from MLP_HEADER_VIEW where REMOVEFLAG = \'F\' ',
  columns: [
    {label: '标识', name: '[IDENTITY]', isQuery: true},
    {label: '名称', name: 'NAME', isQuery: true},
    {label: '描述', name: 'DESCRIPTION', isQuery: true},
    {label: '样品类型', name: 'U_SAMPLE_TYPE', isQuery: true},
  ],
  page:{
    isPage: true,
    order: '[IDENTITY]',
  },
  valueFiled:'NAME',
  order: [{field: 'NAME', dir: 'ASC'}]
})
const testConfig = ref({
  sql: 'select [IDENTITY], NAME, DESCRIPTION from TEST_SCHED_HEADER where REMOVEFLAG = \'F\' ' ,
  columns: [
    {label: '标识', name: '[IDENTITY]', isQuery: true},
    {label: '名称', name: 'NAME', isQuery: true},
    {label: '描述', name: 'DESCRIPTION', isQuery: true},
  ],
  page:{
    isPage: true,
    order: '[IDENTITY]',
  },
  valueFiled:'NAME',
  where:'',
})

const detailList = ref([])

const testList = ref([])

const detailTable = ref()


const onProductSelected = (value) => {
  formData.value.S_MATERIAL_ID = value.IDENTITY
}
/**
 * 规格指标选择
 * @param val
 */
const onSpecSelected = (val) =>{
  console.log('the select value is ::', val)
  formData.value.MLP_ID = val.IDENTITY
  formData.value.TEST_SCHEDULE = val.TEST_SCHEDULE
}
const onTestScheduleSelected = (value) => {
  formData.value.TEST_SCHEDULE = value.IDENTITY
}

const watchTestSchedule = async (value) => {
  try {
    const res = await getVersionAnalysis(value);
    if (res.success) {
      detailList.value = res.data;
      console.log('res.data is :::: ', res.data);
      console.log('testList is :::: ', testList.value);
      if (!testList || testList.value.length === 0){
        await nextTick();
        selectTable()
      }else {
        updateSelectedRows()
      }
    }
  } catch (error) {
    console.error('获取版本分析数据时发生错误：', error);
  }
}

watch(() => formData.value.S_MATERIAL_ID, value => {
  console.log('formData.value.S_MATERIAL_ID value is :::', value)
  let querySql = ' select * from MLP_HEADER_VIEW where REMOVEFLAG = \'F\' '
  if (value){
    let config = new LimsConfig('S_MATERIAL')
    config.filters.eq('IDENTITY', value)
    getTableRecord(config).then(response => {
      if (response.success){
         formData.value.productName = response.data[0].NAME
      }
    })
    specConfig.value.sql = querySql + ' and U_S_MATE_ID = \''+ value+'\''
  }
})
watch(() => formData.value.MLP_ID , value => {
  let config = new LimsConfig('MLP_HEADER_VIEW')
  config.filters.eq('IDENTITY', value)
  getTableRecord(config).then(response => {
    if (response.success){
      formData.value.spec = response.data[0].NAME
    }
  })
})
watch(()=> formData.value.TEST_SCHEDULE, value => {
  console.log('formData.value.TEST_SCHEDULE value is :::', value)
  if (value){
    let sql = testConfig.value.sql + ' and [IDENTITY] = \'' + value + '\' '
    console.log('the select sql is :::', sql)
    getDecodeData('sqlserver', sql).then(response => {
      console.log('TEST_SCHEDULE response is :::', response)
      if (response.success){
        let resultData = response.data
        if (resultData && resultData.length > 0){
          formData.value.TEST_SCHEDULE_NAME = resultData[0].NAME
        }
        watchTestSchedule(value)
      }
    })
  }

}, {deep: true})

const selectTable = () => {
  console.log(detailTable.value)
  detailList.value.forEach((row) => {
    if (row.STD_TEST === 'T' && formData.value.TEST_SCHEDULE !== contractAnal.value.TEST_SCHEDULE){
      console.log('row is ::', row)
      detailTable.value.toggleRowSelection(row)
    }
  })
  let rows =  detailTable.value.getSelectionRows()
  console.log('getSelectionRows :::', rows)
}
const clickRow = (row) => {
  console.log('row is ::', row)
  detailTable.value.toggleRowSelection(row)
  let rows =  detailTable.value.getSelectionRows()
  console.log('getSelectionRows :::', rows)
}

const onSelectionChange = (selection) => {
  console.log('selection is ::::', selection)

}

const contractAnal = ref()
const isReceive = ref(false)

const loadContractAnal = () => {
  let href = window.location.href
  let param = parseParams(href)
  isReceive.value = param.isReceive
  let orderId = param.orderId
  if (orderId){
    let config = new LimsConfig('M_CONTRACT_ANALYSIS')
    config.filters.eq('ORDER_ID', orderId)
    getTableRecord(config).then(response => {
      console.log('获取到已保存数据', response)
      if (response.success){
        contractAnal.value = response.data[0]
        formData.value.inspectSubjects = contractAnal.value.INSPECT_SUBJECTS
        formData.value.IS_REPORT = contractAnal.value.IS_REPORT
        formData.value.MLP_ID = contractAnal.value.MLP_ID
        formData.value.TEST_SCHEDULE = contractAnal.value.TEST_SCHEDULE
        formData.value.S_MATERIAL_ID = contractAnal.value.S_MATERIAL_ID
        formData.value.ORIGINAL_NUMBER = contractAnal.value.REPORT_NO
        formData.value.MEMO = contractAnal.value.MEMO
        watchTestSchedule(formData.value.TEST_SCHEDULE)
        getTestList(orderId)
      }
    })
  }
}

/**
 * 获取测试项目
 * @param orderId
 */
const getTestList = (orderId) =>{
  let config = new LimsConfig('MM_CONTRACT_ANAL_TEST_SUBJECT')
  config.filters.eq('ORDER_ID', orderId)
  getTableRecord(config).then(response =>{
    if(response.success){
      selectedRows.value = []
      testList.value = response.data
      updateSelectedRows()
    }
  })
}


const updateSelectedRows = () => {
  selectedRows.value = [];
  const testMap = new Map();

  // Create a map of test items using a unique key based on ANALYSIS_ID and ORDER_NUM
  testList.value.forEach((testItem) => {
    const key = `${testItem.ANALYSIS_ID}_${testItem.ORDER_NUM}`;
    testMap.set(key, testItem.ORDER_ID);
  });
  console.log('testMap.keys ', testMap.keys())

  // Iterate through detail items and add them to selectedRows if a matching test item is found
  detailList.value.forEach((detailItem) => {
    const key = `${detailItem.ANALYSIS_ID}_${detailItem.ORDER_NUM}`;
    console.log('key is ::', key)
    if (testMap.has(key)) {
      console.log('1111111111111111111111111111111')
      detailItem.ORDER_ID = testMap.get(key);
      selectedRows.value.push(detailItem);
    }
  });

  // Toggle row selection for items with ORDER_ID in selectedRows
  selectedRows.value.forEach((row) => {
    if (row.ORDER_ID) {
      detailTable.value.toggleRowSelection(row);
    }
  });
  console.log('--------------------------')
};


const selectedRows = ref([])

const submitForm = (message) => {
  console.log('formData value is :::', formData.value)
  message = message || '保存';
  contractAnal.value.IS_REPORT = formData.value.IS_REPORT
  contractAnal.value.MLP_ID = formData.value.MLP_ID
  contractAnal.value.TEST_SCHEDULE = formData.value.TEST_SCHEDULE
  contractAnal.value.S_MATERIAL_ID = formData.value.S_MATERIAL_ID
  contractAnal.value.MEMO  = formData.value.MEMO
  let model = Object.assign({}, contractAnal.value)
  let formModel = new LimsFormConfig('M_CONTRACT_ANALYSIS', model, 'edit')
  let rows = detailTable.value.getSelectionRows()
  if (rows.length > 0){
    let detailTestList = []
    rows.forEach(row => {
      let detail = Object.assign({}, row)
      detailTestList.push(detail)
    })
    formModel.addChild('MM_CONTRACT_ANAL_TEST_SUBJECT', detailTestList)
  }
  saveFormData(formModel).then(response => {
    if (response.success){
      console.log('message is ::::: ',message)
      proxy.$modal.msgSuccess(message + '成功')
    }else {
      proxy.$modal.msgError(message + '失败: '+response.message)
    }
  })
  console.log('submitData is ::', formModel)
}

const workFlowTemplateId = ref('3DECCDD3-0535-4103-B8D0-68CCE55CD07D')
/**
 * 提交带
 */
const commitWorkflow = () => {
  console.log('开始提交待开订单：：：',contractAnal.value)
  getActionStatusMapByTemplate(workFlowTemplateId.value).then(response => {
    let action = response.data[0].identity
    console.log('action is :::', action)
    saveWorkFlow(workFlowTemplateId.value, action, '','').then(response =>{
      console.log('保存工作流信息：：', response)
      if (response.success){
        contractAnal.value.WORKFLOW_ID = response.data.identity
        submitForm('提交')
      }
    })
  })
}

const test = () => {
  console.log('开始提交待开订单：：：', contractAnal.value)
  getActionStatusMapByTemplate(workFlowTemplateId.value).then(response => {
    console.log('response is :::', response)

    let action = response.data[0].identity
    let startAction = response.data[0].startStatusModel
    console.log('action is :::', action)
    console.log('startAction is :::', startAction)
    saveWorkFlow(workFlowTemplateId.value, startAction.identity, '','').then(response =>{
      console.log('保存工作流信息：：', response)
      if (response.success){
        contractAnal.value.WORKFLOW_ID = response.data.identity
        submitForm('提交')
      }
    })

  })
}

/**
 * 接收样品
 */
const receiveSample = () =>{
  console.log('-------receiveSample---formData', formData.value)
  console.log('-------receiveSample---contractAnal', contractAnal.value)
  let reqData = {
    sample:{
      LOCATION_ID: "",
      SAMPLING_POINT: "",
      U_SHIPNO: "",
      SUPPLIER_ID: "",
      U_BATCH_NUM: "",
      U_POINT: "临时采样点",
      U_LOCATION: "",
      BATCH_ID: "",
      REPORT_FILE_NUM: "",
      TEMPLATE_ID: "BLANK",
      LONGIN_COUNT: 1,
      ORIGINAL_NUMBER: formData.value.ORIGINAL_NUMBER,
      SAMPLE_NAME: contractAnal.value.SAMPLE_NAME,
      SAMPLE_TYPE: contractAnal.value.INSPECT_REPORT_APT,
      GROUP_ID: contractAnal.value.GROUP_ID,
      U_ANALTYPE: contractAnal.value.INSPECT_TYPE,
      PRODUCT: formData.value.MLP_ID,
      PRODUCT_VERSION:'1',
      TEST_SCHEDULE:formData.value.TEST_SCHEDULE,
      DESCRIPTION:formData.value.MEMO,
      SAMPLED_DATE:moment().format('YYYY-MM-DD HH:mm:ss'),
      U_SAMPLED_BY: "TEST05",
      U_YPSL: "",

    },
    test:[]
  }
  detailTable.value.getSelectionRows().forEach(item => {
    let test = Object.assign({}, item)
    test.COUNT = 1
    setNullToEmpty(test)
    reqData.test.push(test)
  })
  sampleLog(reqData).then(response => {
    console.log('保存样品信息：：：：', response)
    if (response.success){
      submitReceiveWorkflow()
      close()
    }else {
      proxy.$modal.msgError('样品接收失败：'+response.message)
    }
  })
}


const submitReceiveWorkflow = () =>{
  /**查询流程下一个状态 */
  console.log(contractAnal.value.WORKFLOW_ID)
  getActionStatusMapByTemplate(contractAnal.value.WORKFLOW_ID).then(response => {
    console.log('查询流程下一个状态：', response)
    if (response.success){
      console.log('查询流程下一个状态：', response)
    }
  })
}


const close = () => {
  window.parent.closeCallBack()
}

loadContractAnal()
</script>

<template>
    <el-form ref="sampleForm" :model="formData" label-width="120">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="产品编号">
            <el-input v-model="formData.ORIGINAL_NUMBER"  placeholder="请输入产品编号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="检验项目">
            <el-input v-model="formData.inspectSubjects" type="textarea" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="是否测试报告" prop="IS_REPORT">
            <el-radio-group v-model="formData.IS_REPORT">
              <el-radio label="是"></el-radio>
              <el-radio label="否"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="产品" prop="productName">
            <input-table v-model="formData.productName" title="选择产品" placeholder="请选择产品"
                         :field="queryConfig.valueFiled"
                         :sql="queryConfig.sql"
                         :columns="queryConfig.columns"
                         @on-selected="onProductSelected"
            ></input-table>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="规格指标">
            <input-table v-model="formData.spec" title="选择产品规格指标" placeholder="请选择产品规格指标"
                         :field="specConfig.valueFiled"
                         :sql="specConfig.sql"
                         :order="specConfig.order"
                         :columns="specConfig.columns"
                         @on-selected="onSpecSelected"
            ></input-table>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="测试包" prop="TEST_SCHEDULE_NAME">
            <input-table v-model="formData.TEST_SCHEDULE_NAME" title="选择测试包" placeholder="请选择测试包"
                         :field="testConfig.valueFiled"
                         :sql="testConfig.sql + testConfig.where"
                         :columns="testConfig.columns"
                         @on-selected="onTestScheduleSelected"
            ></input-table>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="MEMO">
            <el-input v-model="formData.MEMO" type="textarea" rows="4"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="">
            <el-button type="primary" v-if="isReceive" @click="receiveSample">接收样品</el-button>
            <el-button type="primary" v-if="!isReceive" @click="submitForm('保存')">保存</el-button>
            <el-button type="primary" v-if="!isReceive" @click="commitWorkflow">提交</el-button>
            <el-button type="primary" @click="close">关闭</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-divider>测试项目</el-divider>
    <el-table ref="detailTable" @row-click="clickRow"  @selection-change="onSelectionChange"  :data="detailList" height="400">
      <el-table-column type="selection"></el-table-column>
<!--      <el-table-column prop="IDENTITY" label="标识"></el-table-column>-->
      <el-table-column prop="ORDER_NUM" label="序号"></el-table-column>
      <el-table-column prop="ANALYSIS_ID" label="分析方法"></el-table-column>
      <el-table-column prop="STD_TEST" label="测试标准"></el-table-column>
      <el-table-column prop="U_S_ANAL_ID" label="分析项目"></el-table-column>
    </el-table>
</template>

<style scoped lang="scss">

</style>